package com.example.springmvc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

import com.example.springmvc.domain.CourseInfo;
import com.example.springmvc.domain.StudentInfo;

public class CourseDaoImpl implements DaoBase {

	private DataSource dataSource;
	
	@Autowired
	public void setDataSource(DataSource dataSource){
		this.dataSource = dataSource;
	}
	
	public List selectAll() throws SQLException {

		String sql = "SELECT * FROM COURSE_INFO";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<CourseInfo> results = new ArrayList<CourseInfo>();
		List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
		
		for(Map<String, Object> row : rows){
			CourseInfo courseInfo = new CourseInfo();
			courseInfo.setCourse_code((String) row.get("COURSE_CODE"));
			courseInfo.setCourse_name((String) row.get("COURSE_NAME"));
			courseInfo.setCourse_period((String) row.get("COURSE_PERIOD"));
			courseInfo.setCourse_summary((String) row.get("COURSE_SUMMARY"));
						
			results.add(courseInfo);
		}
		
		return results;
	}

	public Object selectById(String id) throws SQLException {

		String sql = "SELECT * FROM COURSE_INFO WHERE COURSE_CODE=?";
		
		final CourseInfo courseInfo = new CourseInfo();
		
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.query(sql, new Object[]{ id },
				new RowCallbackHandler(){

					public void processRow(ResultSet rs) throws SQLException {
						// Mapping
						courseInfo.setCourse_code(rs.getString("COURSE_CODE"));
						courseInfo.setCourse_name(rs.getString("COURSE_NAME"));
						courseInfo.setCourse_period(rs.getString("COURSE_PERIOD"));
						courseInfo.setCourse_summary(rs.getString("COURSE_SUMMARY"));	
					}
				});
		return (Object)courseInfo;
		
	}

	public boolean update(Object o) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean delete(String id) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean insert(Object o) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	public String checkLogIn(String id, String passwd) {
		// TODO Auto-generated method stub
		return null;
	}

}
